import React, { useContext } from "react";

import AsyncStorage from "@react-native-async-storage/async-storage";
import queryApi from "../api/query";
import createDataContext from "./createDataContext";

import * as RootNavigation from "../RootNavigation";

export const authReducer = (state, action) => {
  switch (action.type) {
    case "add_error":
      return { ...state, errorMessage: action.payload };
    case "signup":
      return { errorMessage: "", token: action.payload };
    case "signout":
      return { errorMessage: "", token: action.payload };
    default:
      return state;
  }
};

const signup =
  (dispatch) =>
  async ({ email, password }) => {
    // make api request to sign up with that email and password
    // if we sign up, modify our state, and say that we are authenticated
    //if signing up fails, we probably need to reflect an error message somewhere
    try {
      const response = await queryApi.post("/user/signup", { email, password });

      await AsyncStorage.setItem("token", response.data.token);
      dispatch({ type: "signup", payload: response.data.token });

      RootNavigation.navigate("HomeDrawer");
    } catch (error) {
      dispatch({
        type: "add_error",
        payload: "Something went wrong with signup",
      });
    }
  };

const signin = (dispatch) => {
  return ({ email, password }) => {
    // Try to signin
    // Handle success by updating state
    //Handle failure by showing error message(somehow)
    // const userToken = String(foundUser[0].userToken);
    // try {
    //   userToken = 'zhahgh';
    //   await AsyncStorage.setItem('userToken', userToken);
    // } catch (error) {
    //   console.log(error);
    // }
    // dispatch({ type: 'LOGIN', id: 'fjdsk', token: userToken });
  };
};

const signout = (dispatch) => {
  return async () => {
    // JUST sign out
    console.log("I M LEAVING:  1");
    try {
      await AsyncStorage.removeItem("userToken");
      console.log("I M LEAVING:  2");
      dispatch({ type: "signout", payload: null });
      console.log("I M LEAVING:  3");

      RootNavigation.navigate("Detail");
    } catch (error) {
      console.log("I M LEAVING:  4");
      console.log(error);
    }
  };
};

export const { Provider, Context } = createDataContext(
  authReducer,
  { signin, signout, signup },
  { token: null, errorMessage: "" }
);

export function useHelper() {
  const { state } = useContext(Context);
  const test = () => console.log(state);
  return { test };
}
